import { _decorator, Component, Node, Button, Label } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { EditBox } from 'cc';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { BindEditBox } from '../../../../scripts/libs/rxjs/cc3/BindEditBox';
import { Observable } from 'rxjs';
import { ReactiveCommand } from '../../../../scripts/libs/rxjs/cc3/ReactiveCommand';
import { BindNodeMouse } from '../../../../scripts/libs/rxjs/cc3/BindNode';
import { gm } from '../../../../scripts/managers/GameManager';
import { NodeEventType } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EditorInspectorString')
export class EditorInspectorString extends BaseView {

    getRP: () => ReactiveProperty<string> = null;

    @property(Button)
    selfButton: Button = null;

    @property(EditBox)
    editBox: EditBox = null;

    @property(Label)
    valueLabel: Label = null;

    editMode = ReactiveProperty.Create(false);

    changedCommand = ReactiveCommand.Create<string>();

    useObserves() {
        return [
            this.editMode.subscribe(_ => {
                this.editBox.node.active = _;
                this.valueLabel.node.active = !_;
                this.refresh();
                if (this.editMode.value) this.editBox.focus();
            }),
            BindButton(this.selfButton).subscribe(_ => this.editMode.value = !this.editMode.value),
            BindEditBox(this.editBox).subscribe(_ => {
                if (_.eventType == EditBox.EventType.EDITING_DID_ENDED) {
                    if (this.editBox.string != '') {
                        let targetValue = this.editBox.string;
                        if (targetValue != null) {
                            this.getRP().value = targetValue;
                            this.changedCommand.execute(targetValue);
                            this.editMode.value = false;
                        }
                    } else {
                        this.getRP().value = null;
                        this.changedCommand.execute(null);
                        this.editMode.value = false;
                    }
                }
            })
        ];
    }

    setGetRP(f: () => ReactiveProperty<string>) {
        this.getRP = f;
        this.refresh();
    }

    refresh() {
        this.editBox.string = `${this.getRP?.()?.value ?? ''}`;
        this.valueLabel.string = `${this.labelFilter(this.getRP?.()?.value)}`;
    }

    labelFilter = (str: any) => {
        return `${str ?? 'n/a'}`;
    }

}